package com.gaojinqi.sys.modular.rbac.controller;

import com.gaojinqi.base.common.exception.BizRuntimeException;
import com.gaojinqi.base.common.model.PageReq;
import com.gaojinqi.base.common.validation.group.Insert;
import com.gaojinqi.base.common.validation.group.Update;
import com.gaojinqi.base.common.vo.IResult;
import com.gaojinqi.base.common.vo.PageResultVo;
import com.gaojinqi.base.common.vo.ResultVo;
import com.gaojinqi.sys.modular.rbac.model.Permission;
import com.gaojinqi.sys.modular.rbac.model.Role;
import com.gaojinqi.sys.modular.rbac.service.PermissionService;
import com.gaojinqi.sys.modular.rbac.service.RoleService;
import com.gaojinqi.sys.modular.rbac.vo.RoleSaveVo;
import com.gaojinqi.sys.modular.rbac.vo.RoleSearchVo;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.StringProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.Collection;
import java.util.Objects;

/**
 * 角色 控制器
 *
 * @author gaojinqi
 * @version 1.0
 * @since 2020年05月19日
 */
@Api(tags = "角色")
@RestController
@Validated
@Slf4j
@RequestMapping(value = "/role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @ApiOperation(value = "新增角色")
    @PostMapping
    public IResult<Role> addRole(@Validated(Insert.class) @RequestBody RoleSaveVo param) {
        Role role = roleService.findByRole(param.getRole());
        if (role != null) {
            throw new BizRuntimeException("该角色编码已存在");
        }
        Role entity = new Role();
        BeanUtils.copyProperties(param, entity);
        if (entity.getSort() == null) {
            entity.setSort(0);
        }
        roleService.save(entity);
        return ResultVo.suc(entity);
    }

    @ApiOperation(value = "修改角色")
    @PutMapping(value = "/{roleId}")
    public IResult<Role> updateRole(
            @NotBlank(message = "请输入角色ID") @PathVariable(value = "roleId") String roleId,
            @Validated(Update.class) @RequestBody RoleSaveVo param) {
        Role role = roleService.findByRole(param.getRole());
        if (role != null && !Objects.equals(role.getRoleId(), roleId)) {
            throw new BizRuntimeException("该角色编码已存在");
        }
        Role entity = new Role();
        entity.setRoleId(roleId);
        BeanUtils.copyProperties(param, entity);
        roleService.update(entity);
        return ResultVo.suc(entity);
    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping(value = "/{roleIds}")
    @ApiImplicitParam(name = "roleIds", value = "角色ID list", allowMultiple = true, paramType = "path", dataType = StringProperty.TYPE, required = true)
    public IResult<String> deleRole(
            @NotEmpty(message = "请输入角色ID") @PathVariable(value = "roleIds") String[] roleIds) {
        roleService.deleteByIds(Lists.newArrayList(roleIds));
        return ResultVo.suc("删除成功");
    }

    @ApiOperation(value = "根据ID查询角色详情")
    @GetMapping(value = "/{roleId}")
    public IResult<Role> getRole(
            @NotBlank(message = "请输入角色ID") @PathVariable(value = "roleId") String roleId) {
        return ResultVo.suc(roleService.findById(roleId));
    }

    @ApiOperation(value = "分页查询角色")
    @GetMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", dataType = IntegerProperty.TYPE, paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页条目数量", dataType = IntegerProperty.TYPE, defaultValue = "10", paramType = "query"),
            @ApiImplicitParam(name = "sortMode", value = "排序方式，倒序为0，正序为1", dataType = IntegerProperty.TYPE, defaultValue = "0", paramType = "query"),
    })
    public IResult<Collection<Role>> page(RoleSearchVo param, PageReq pageReq) {
        Role entity = new Role();
        BeanUtils.copyProperties(param, entity);
        return PageResultVo.suc(roleService.page(entity, pageReq));
    }

    @ApiOperation(value = "查询指定角色已分配的权限")
    @GetMapping("/{roleId}/perm")
    public IResult<Collection<Permission>> findAssignedPermsByRoleId(
            @NotBlank(message = "请选择角色") @PathVariable(value = "roleId") String roleId) {
        return ResultVo.suc(permissionService.findPermsByRoleId(roleId));
    }

    @ApiOperation(value = "给指定角色分配权限")
    @PutMapping("/{roleId}/perm")
    @ApiImplicitParam(name = "permIds", value = "权限ID集合", dataType = StringProperty.TYPE, allowMultiple = true, paramType = "query")
    public IResult<Object> assignPermsToRoleId(
            @NotBlank(message = "请选择角色") @PathVariable(value = "roleId") String roleId,
            @NotEmpty(message = "请选择要分配的权限") String[] permIds) {
        permissionService.assignPermsToRoleId(roleId, Sets.newHashSet(permIds));
        return ResultVo.suc("分配权限成功");
    }


}
